/*
* Copyright 2017 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-service-dealer
*
* @File name : TestDrivingService.java
*
* @Author : Administrator
*
* @Date : 2017年12月5日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2017年12月5日    Administrator    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/

package com.yonyou.gmmc.service.dealer.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.marketing.common.dto.freeTime.FreeTimeDto;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.util.CheckUtil;
import org.marketing.common.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ibm.icu.util.Calendar;
import com.yonyou.gmmc.common.sms.SmsHttpClient2;
import com.yonyou.gmmc.service.dealer.constant.DealerConstant;
import com.yonyou.gmmc.service.dealer.dao.TmDealerMapper;
import com.yonyou.gmmc.service.dealer.dao.TmEvaluationDetailMapper;
import com.yonyou.gmmc.service.dealer.dao.TmRegionMapper;
import com.yonyou.gmmc.service.dealer.dao.TmUsersMapper;
import com.yonyou.gmmc.service.dealer.dao.TmVirtualCenterMapper;
import com.yonyou.gmmc.service.dealer.dao.TrDriveGoodsRelationMapper;
import com.yonyou.gmmc.service.dealer.dao.TrUserEnterpriseMapper;
import com.yonyou.gmmc.service.dealer.dao.TtDriveEvaluationMapper;
import com.yonyou.gmmc.service.dealer.dao.TtDriveEvaluationResultMapper;
import com.yonyou.gmmc.service.dealer.dao.TtDriveGoodsMapper;
import com.yonyou.gmmc.service.dealer.dao.TtDriveInfoMapper;
import com.yonyou.gmmc.service.dealer.dao.TtTestdriveMapper;
import com.yonyou.gmmc.service.dealer.entity.EvaluationPO;
import com.yonyou.gmmc.service.dealer.entity.EvaluationResultPO;
import com.yonyou.gmmc.service.dealer.entity.TestdrivePO;
import com.yonyou.gmmc.service.dealer.model.TmDealer;
import com.yonyou.gmmc.service.dealer.model.TmEvaluationDetail;
import com.yonyou.gmmc.service.dealer.model.TmRegion;
import com.yonyou.gmmc.service.dealer.model.TmUsers;
import com.yonyou.gmmc.service.dealer.model.TmVirtualCenter;
import com.yonyou.gmmc.service.dealer.model.TrDriveGoodsRelation;
import com.yonyou.gmmc.service.dealer.model.TrUserEnterprise;
import com.yonyou.gmmc.service.dealer.model.TtDriveEvaluation;
import com.yonyou.gmmc.service.dealer.model.TtDriveEvaluationResult;
import com.yonyou.gmmc.service.dealer.model.TtDriveGoods;
import com.yonyou.gmmc.service.dealer.model.TtDriveInfo;
import com.yonyou.gmmc.service.dealer.model.TtTestdrive;
import com.yonyou.gmmc.service.dealer.util.DloadImgFromQy;

import tk.mybatis.mapper.entity.Example;

/**
 * @author Administrator
 * @date 2017年12月5日
 */

@Service
@Transactional
public class TestDrivingService {

    private Logger                        logger = Logger.getLogger(TestDrivingService.class);

    @Autowired
    private TtTestdriveMapper             ttTestdriveMapper;

    @Autowired
    private TmUsersMapper                 tmUsersMapper;

    @Autowired
    private TtDriveEvaluationMapper       ttDriveEvaluationMapper;

    @Autowired
    private TtDriveEvaluationResultMapper ttDriveEvaluationResultMapper;

    @Autowired
    private TmEvaluationDetailMapper      tmEvaluationDetailMapper;

    @Autowired
    private TmVirtualCenterMapper         tmVirtualCenterMapper;

    @Autowired
    private TmDealerMapper                tmDealerMapper;

    @Autowired
    private TmRegionMapper                tmRegionMapper;

    @Autowired
    private TrUserEnterpriseMapper        trUserEnterpriseMapper;

    @Autowired
    private TrDriveGoodsRelationMapper    trDriveGoodsRelationMapper;

    @Autowired
    private TtDriveGoodsMapper            ttDriveGoodsMapper;

    @Autowired
    private TtDriveInfoMapper             ttDriveInfoMapper;

    @Value("${SMS-pass}")
    private String                        smsPass;
    @Value("${SMS-key}")
    private String                        smsKey;
    @Value("${SMS_TEMPLATEID_SC}")
    private String                        SMS_TEMPLATEID_SC;

    /**
     * 保存试驾预约
     * 
     * @author Administrator
     * @date 2017年12月11日
     * @param ttTestdrive
     * @return
     * @throws Exception
     */
    public Map<String, Object> saveDrive(TtTestdrive ttTestdrive) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            if (CheckUtil.NullOrEmpty(ttTestdrive.getSex())) {
                result.put("errorCode", "0");
                result.put("errorMsg", "称呼不可为空");
                return result;
            }
            if (CheckUtil.NullOrEmpty(ttTestdrive.getUserName())) {
                result.put("errorCode", "0");
                result.put("errorMsg", "预约人姓名不可为空");
                return result;
            }
            if (CheckUtil.NullOrEmpty(ttTestdrive.getUserPhone())) {
                result.put("errorCode", "0");
                result.put("errorMsg", "联系人电话不可为空");
                return result;
            }
            if (CheckUtil.NullOrEmpty(ttTestdrive.getProviceCode()) || CheckUtil.NullOrEmpty(ttTestdrive.getCityCode())
                || CheckUtil.NullOrEmpty(ttTestdrive.getAddress())) {
                result.put("errorCode", "0");
                result.put("errorMsg", "试驾地址不可为空");
                return result;
            }
            if (CheckUtil.NullOrEmpty(ttTestdrive.getModelCodeNew())) {
                result.put("errorCode", "0");
                result.put("errorMsg", "试驾车型不可为空");
                return result;
            }
            if (CheckUtil.NullOrEmpty(ttTestdrive.getApplyTime())) {
                result.put("errorCode", "0");
                result.put("errorMsg", "预约时间不可为空");
                return result;
            }
            ttTestdrive.setCreateBy(DealerConstant.CREATE_USER.longValue());
            ttTestdrive.setStatus(DealerConstant.TESTDRIVING_WAITING_DISPATCH);
            int a = ttTestdriveMapper.saveDrive(ttTestdrive);
            if (a == 1) {
                result.put("errorCode", "1");
                result.put("errorMsg", "保存试驾预约成功");
                return result;
            } else {
                result.put("errorCode", "0");
                result.put("errorMsg", "保存试驾预约失败");
                return result;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
     * 查询新建试驾的编号
     * 
     * @author AdministratorS
     * @date 2017年12月11日
     * @return
     * @throws Exception
     */
    public String selectDriveId() throws Exception {
        String driveId = null;
        try {
            driveId = ttTestdriveMapper.selectDriveId();
            if (CheckUtil.NullOrEmpty(driveId)) {
                throw new ServiceBizException("查询试驾编号异常");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
        return driveId;
    }

    /**
     * PC-查询试驾预约列表
     * 
     * @author Administrator
     * @date 2017年12月11日
     * @param query
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unused")
    public PageInfo<TtTestdrive> selectDriveList(Map<String, Object> query) throws Exception {
        List<TtTestdrive> list = new ArrayList<TtTestdrive>();
        try {
            String position = tmUsersMapper.selectPosition(query.get("userId").toString());
            if (position.equals("702")) {
                query.put("manager", query.get("userId").toString());
            } else if (position.equals("703")) {
                query.put("counselor", query.get("userId").toString());
            } else if (position.equals("704")) {
                query.put("appreciationEngineer", query.get("userId").toString());
            } else {
                query.put("manager", "");
                query.put("counselor", "");
                query.put("appreciationEngineer", "");
            }
            Page<TtTestdrive> ss = PageHelper.startPage(Integer.parseInt(query.get("pageNum").toString()),
                                                        Integer.parseInt(query.get("pageSize").toString()));

            list = ttTestdriveMapper.selectDriveList(query);
            PageInfo<TtTestdrive> page = new PageInfo<TtTestdrive>(list);
            return page;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
     * 企业号-经理查看试驾列表
     * 
     * @author Administrator
     * @date 2017年12月19日
     * @param query
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unused")
    public PageInfo<TtTestdrive> managerList(Map<String, Object> query) throws Exception {
        List<TtTestdrive> list = new ArrayList<TtTestdrive>();
        logger.info("入参：" + query);
        try {
            Example example = new Example(TmUsers.class);
            example.createCriteria().andCondition("PHONE=", query.get("phone").toString());
            example.createCriteria().andCondition("WX_USER_ID", query.get("wxUserId").toString());
            List<TrUserEnterprise> trList = trUserEnterpriseMapper.selectByExample(example);
            if (trList.size() > 0) {
                query.put("userId", trList.get(0).getUserId());
            } else {
                throw new ServiceBizException("获取人员信息异常，请联系管理员校验！");
            }
            Page<TtTestdrive> ss = PageHelper.startPage(Integer.parseInt(query.get("pageNum").toString()),
                                                        Integer.parseInt(query.get("pageSize").toString()));

            list = ttTestdriveMapper.selectDriveListByManager(query);
            PageInfo<TtTestdrive> page = new PageInfo<TtTestdrive>(list);
            return page;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
     * 企业号-顾问查看试驾列表
     * 
     * @author Administrator
     * @date 2017年12月19日
     * @param query
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unused")
    public PageInfo<TtTestdrive> counselorList(Map<String, Object> query) throws Exception {
        List<TtTestdrive> list = new ArrayList<TtTestdrive>();
        try {
            Example example = new Example(TmUsers.class);
            example.createCriteria().andCondition("PHONE=", query.get("phone").toString());
            example.createCriteria().andCondition("WX_USER_ID", query.get("wxUserId").toString());
            List<TrUserEnterprise> trList = trUserEnterpriseMapper.selectByExample(example);
            if (trList.size() > 0) {
                query.put("userId", trList.get(0).getUserId());
            } else {
                throw new ServiceBizException("获取人员信息异常，请联系管理员校验！");
            }
            Page<TtTestdrive> ss = PageHelper.startPage(Integer.parseInt(query.get("pageNum").toString()),
                                                        Integer.parseInt(query.get("pageSize").toString()));

            list = ttTestdriveMapper.selectDriveListByCounselor(query);
            PageInfo<TtTestdrive> page = new PageInfo<TtTestdrive>(list);
            return page;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
     * 企业号-鉴赏工程师查看试驾列表
     * 
     * @author Administrator
     * @date 2017年12月19日
     * @param query
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unused")
    public PageInfo<TtTestdrive> engineerList(Map<String, Object> query) throws Exception {
        List<TtTestdrive> list = new ArrayList<TtTestdrive>();
        try {
            Example example = new Example(TmUsers.class);
            example.createCriteria().andCondition("PHONE=", query.get("phone").toString());
            example.createCriteria().andCondition("WX_USER_ID", query.get("wxUserId").toString());
            List<TrUserEnterprise> trList = trUserEnterpriseMapper.selectByExample(example);
            if (trList.size() > 0) {
                query.put("userId", trList.get(0).getUserId());
            } else {
                throw new ServiceBizException("获取人员信息异常，请联系管理员校验！");
            }
            Page<TtTestdrive> ss = PageHelper.startPage(Integer.parseInt(query.get("pageNum").toString()),
                                                        Integer.parseInt(query.get("pageSize").toString()));

            list = ttTestdriveMapper.selectDriveListByEngineer(query);
            PageInfo<TtTestdrive> page = new PageInfo<TtTestdrive>(list);
            return page;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
     * 单条试驾预约详情查询
     * 
     * @author Administrator
     * @date 2017年12月13日
     * @param driveId
     * @return
     * @throws Exception
     */
    public TtTestdrive driverInfo(String driveId) throws Exception {
        TtTestdrive result = new TtTestdrive();
        try {
            List<TtTestdrive> list = ttTestdriveMapper.selectDriverInfo(driveId);
            if (list.size() > 0) {
                result = list.get(0);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 客服分拨
     * 
     * @author Administrator
     * @date 2017年12月13日
     * @param ttTestdrive
     * @return
     * @throws Exception
     */
    public Map<String, Object> dispatch(TtTestdrive ttTestdrive) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            if (CheckUtil.NullOrEmpty(ttTestdrive.getDriveId())) {
                result.put("errorCode", "0");
                result.put("errorMsg", "预约单编号不可为空");
                return result;
            }
            if (CheckUtil.NullOrEmpty(ttTestdrive.getLicenseNo())) {
                result.put("errorCode", "0");
                result.put("errorMsg", "试驾车辆不可为空");
                return result;
            }
            if (CheckUtil.NullOrEmpty(ttTestdrive.getDispatchObject())) {
                result.put("errorCode", "0");
                result.put("errorMsg", "分拨对象不可为空");
                return result;
            }
            if (CheckUtil.NullOrEmpty(ttTestdrive.getAppreciationEngineer())) {
                result.put("errorCode", "0");
                result.put("errorMsg", "鉴赏工程师不可为空");
                return result;
            }
            Example ex = new Example(TmUsers.class);
            ex.createCriteria().andCondition("VIRTUAL_CENTER=", ttTestdrive.getDispatchObject());
            List<TmUsers> user = tmUsersMapper.selectByExample(ex);
            if (user.size() > 0) {
                ttTestdrive.setManager(user.get(0).getUserId().toString());
            } else {
                result.put("errorCode", "0");
                result.put("errorMsg", "分拨异常，请重新尝试");
                return result;
            }
            Example example = new Example(TtTestdrive.class);
            example.createCriteria().andCondition("DRIVE_ID=", ttTestdrive.getDriveId());
            ttTestdrive.setUpdateBy(DealerConstant.TESTDRIVING_DISPATCH_UPDATE);
            ttTestdrive.setUpdateDate(new Date());
            ttTestdrive.setStatus(DealerConstant.TESTDRIVING_WAITING_LIST);
            int a = ttTestdriveMapper.updateByExampleSelective(ttTestdrive, example);
            if (a == 1) {
                result.put("errorCode", "1");
                result.put("errorMsg", "分拨该预约单成功");
                logger.info("分拨成功，发送预约成功短信");
                List<TtTestdrive> list = ttTestdriveMapper.selectDriverInfo(ttTestdrive.getDriveId().toString());
                String phone = list.get(0).getUserPhone();
                TtTestdrive dto = driverInfo(ttTestdrive.getDriveId().toString());
                String content = "亲爱的客户，您的试驾预约已成功！为您安排的试驾车型为" + dto.getModelCodeNew() + "，车牌号" + dto.getLicenseNo()
                                 + "。我们的鉴赏工程师" + dto.getAppreciationEngineer() + "，联系电话" + dto.getEngineerPhone()
                                 + "，将在" + dto.getApplyTime() + "恭候您的到来， 届时请您准备好驾驶证，谢谢！试驾地址：" + dto.getAddress() + "。";
                String s = SmsHttpClient2.sendSms(smsPass, smsKey, SMS_TEMPLATEID_SC, phone, content);
                logger.info("短信返回状态为：" + s);
                return result;
            } else {
                result.put("errorCode", "0");
                result.put("errorMsg", "分拨该预约单失败");
                return result;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
     * 经理接单
     * 
     * @author Administrator
     * @date 2017年12月14日
     * @param ttTestdrive
     * @return
     * @throws Exception
     */
    public Map<String, Object> manager(TtTestdrive ttTestdrive) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            if (CheckUtil.NullOrEmpty(ttTestdrive.getDriveId())) {
                result.put("errorCode", "0");
                result.put("errorMsg", "预约单编号不可为空");
                return result;
            }
            if (CheckUtil.NullOrEmpty(ttTestdrive.getCounselor())) {
                result.put("errorCode", "0");
                result.put("errorMsg", "首席顾问不可为空");
                return result;
            }
            Example example = new Example(TtTestdrive.class);
            example.createCriteria().andCondition("DRIVE_ID=", ttTestdrive.getDriveId());
            ttTestdrive.setUpdateBy(DealerConstant.TESTDRIVING_MANAGER_UPDATE);
            ttTestdrive.setUpdateDate(new Date());
            ttTestdrive.setStatus(DealerConstant.TESTDRIVING_WAITING_SURE);
            int a = ttTestdriveMapper.updateByExampleSelective(ttTestdrive, example);
            if (a == 1) {
                result.put("errorCode", "1");
                result.put("errorMsg", "经理接单成功");
                return result;
            } else {
                result.put("errorCode", "0");
                result.put("errorMsg", "经理接单失败");
                return result;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
     * 经理接单-无法响应
     * 
     * @author Administrator
     * @date 2017年12月14日
     * @param driveId
     * @return
     * @throws Exception
     */
    public Map<String, Object> unableToRespond(String driveId) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            TtTestdrive ttTestdrive = new TtTestdrive();
            ttTestdrive.setUpdateBy(DealerConstant.TESTDRIVING_MANAGER_UPDATE);
            ttTestdrive.setUpdateDate(new Date());
            ttTestdrive.setStatus(DealerConstant.TESTDRIVING_STATUS_CANCELED);
            Example example = new Example(TtTestdrive.class);
            example.createCriteria().andCondition("DRIVE_ID=", driveId);
            int a = ttTestdriveMapper.updateByExampleSelective(ttTestdrive, example);
            if (a == 1) {
                result.put("errorCode", "1");
                result.put("errorMsg", "该单已处理为-无法响应");
            } else {
                result.put("errorCode", "0");
                result.put("errorMsg", "该单处理失败，请重新处理");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 顾问确认
     * 
     * @author Administrator
     * @date 2017年12月14日
     * @param ttTestdrive
     * @return
     * @throws Exception
     */
    public Map<String, Object> confirmOrder(TtTestdrive ttTestdrive) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            if (CheckUtil.NullOrEmpty(ttTestdrive.getDriveId())) {
                result.put("errorCode", "0");
                result.put("errorMsg", "预约单编号不可为空");
                return result;
            }
            if (CheckUtil.NullOrEmpty(ttTestdrive.getAddress())) {
                result.put("errorCode", "0");
                result.put("errorMsg", "试驾地址不可为空");
                return result;
            }
            if (CheckUtil.NullOrEmpty(ttTestdrive.getModelCodeNew())) {
                result.put("errorCode", "0");
                result.put("errorMsg", "试驾车型不可为空");
                return result;
            }
            if (CheckUtil.NullOrEmpty(ttTestdrive.getApplyTime())) {
                result.put("errorCode", "0");
                result.put("errorMsg", "预约时间不可为空");
                return result;
            }
            if (CheckUtil.NullOrEmpty(ttTestdrive.getLicenseNo())) {
                result.put("errorCode", "0");
                result.put("errorMsg", "试驾车辆不可为空");
                return result;
            }
            if (CheckUtil.NullOrEmpty(ttTestdrive.getAppreciationEngineer())) {
                result.put("errorCode", "0");
                result.put("errorMsg", "鉴赏工程师不可为空");
                return result;
            }
            ttTestdrive.setUpdateBy(DealerConstant.TESTDRIVING_COUNSELOR_UPDATE);
            ttTestdrive.setUpdateDate(new Date());
            ttTestdrive.setStatus(DealerConstant.TESTDRIVING_WAITING_DRIVE);
            Example example = new Example(TtTestdrive.class);
            example.createCriteria().andCondition("DRIVE_ID=", ttTestdrive.getDriveId());
            int a = ttTestdriveMapper.updateByExampleSelective(ttTestdrive, example);
            if (a == 1) {
                result.put("errorCode", "1");
                result.put("errorMsg", "该试驾确认成功");
                logger.info("确认成功，发送预约已确认短信");
                List<TtTestdrive> list = ttTestdriveMapper.selectDriverInfo(ttTestdrive.getDriveId().toString());
                String phone = list.get(0).getUserPhone();
                TtTestdrive dto = driverInfo(ttTestdrive.getDriveId().toString());
                String content = "亲爱的客户，您的试驾预约已确认！为您安排的试驾车型为" + dto.getModelCodeNew() + "，车牌号" + dto.getLicenseNo()
                                 + "。我们的鉴赏工程师" + dto.getAppreciationEngineer() + "，联系电话" + dto.getEngineerPhone()
                                 + "，将在" + dto.getApplyTime() + "恭候您的到来， 届时请您准备好驾驶证，谢谢！试驾地址：" + dto.getAddress() + "。";
                String s = SmsHttpClient2.sendSms(smsPass, smsKey, SMS_TEMPLATEID_SC, phone, content);
                logger.info("短信返回状态为：" + s);
                return result;
            } else {
                result.put("errorCode", "0");
                result.put("errorMsg", "该试驾确认失败");
                return result;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
     * 顾问确认-用户取消预约
     * 
     * @author Administrator
     * @date 2017年12月14日
     * @param driveId
     * @return
     * @throws Exception
     */
    public Map<String, Object> cancel(String driveId) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            int a = ttTestdriveMapper.cancel(driveId);
            if (a == 1) {
                result.put("errorCode", "1");
                result.put("errorMsg", "该预约已成功取消");
            } else {
                result.put("errorCode", "0");
                result.put("errorMsg", "取消预约失败，请重新处理");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 预约提醒
     * 
     * @author Administrator
     * @date 2017年12月14日
     * @return
     * @throws Exception
     */
    public String remind() throws Exception {
        String result = null;
        try {
            List<TtTestdrive> list = ttTestdriveMapper.remind();
            if (list.size() > 0) {
                for (TtTestdrive dto : list) {
                    String phone = dto.getUserPhone();
                    String content = "亲爱的客户，您预约了" + dto.getApplyTime() + "的试驾预约，请您届时到达约定地点，并保持手机通畅！试驾车型："
                                     + dto.getModelCodeNew() + "，车牌号：" + dto.getLicenseNo() + "，鉴赏工程师："
                                     + dto.getAppreciationEngineer() + "，联系电话：" + dto.getEngineerPhone() + "，试驾地址："
                                     + dto.getAddress() + "。";
                    String s = SmsHttpClient2.sendSms(smsPass, smsKey, SMS_TEMPLATEID_SC, phone, content);
                    logger.info("短信返回状态为：" + s);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 鉴赏工程师-立即出发
     * 
     * @author Administrator
     * @date 2017年12月14日
     * @param driveId
     * @return
     * @throws Exception
     */
    public Map<String, Object> start(List<TrDriveGoodsRelation> queryList) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            for (TrDriveGoodsRelation l : queryList) {
                int s = trDriveGoodsRelationMapper.insertSelective(l);
                logger.info("保存了" + s + "条记录");
            }
            int a = ttTestdriveMapper.start(queryList.get(0).getDriveId().toString());
            if (a == 1) {
                result.put("errorCode", "1");
                result.put("errorMsg", "已成功出发");
                logger.info("出发成功，发送提醒短信");
                List<TtTestdrive> list = ttTestdriveMapper.selectDriverInfo(queryList.get(0).getDriveId().toString());
                String phone = list.get(0).getUserPhone();
                TtTestdrive dto = driverInfo(queryList.get(0).getDriveId().toString());
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                String date = sdf.format(dto.getApplyTime());
                String content = "亲爱的客户，您的鉴赏工程师已出发！将于今天上午" + date + "到达约定地点，请保持手机通畅！试驾车型：" + dto.getModelCodeNew()
                                 + "，车牌号：" + dto.getLicenseNo() + "，鉴赏工程师：" + dto.getAppreciationEngineer() + "，联系电话："
                                 + dto.getEngineerPhone() + "，试驾地址：" + dto.getAddress() + "。";
                String s = SmsHttpClient2.sendSms(smsPass, smsKey, SMS_TEMPLATEID_SC, phone, content);
                logger.info("短信返回状态为：" + s);
            } else {
                result.put("errorCode", "0");
                result.put("errorMsg", "出发失败，请重新处理");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 上传试驾协议
     * 
     * @author Administrator
     * @date 2017年12月14日
     * @param ttTestdrive
     * @return
     * @throws Exception
     */
    public Map<String, Object> driveAgreement(TestdrivePO testdrivePO) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<String> list = DloadImgFromQy.downloadMedia(testdrivePO.getDriveMediaIdList(),
                                                             testdrivePO.getAccessToken());
            if (list.size() != 0) {
                TtDriveInfo record = new TtDriveInfo();
                int i = list.size();
                record.setDriveUrl1(list.get(0));
                if(i==2){
                    record.setDriveUrl2(list.get(1));
                }
                if(i==3){
                    record.setDriveUrl2(list.get(1));
                    record.setDriveUrl2(list.get(2));
                }
                if(i==4){
                    record.setDriveUrl2(list.get(1));
                    record.setDriveUrl2(list.get(2));
                    record.setDriveUrl2(list.get(3));
                }
                record.setCreateBy(DealerConstant.CREATE_USER.longValue());
                record.setCreateDate(new Date());
                record.setDriveId(testdrivePO.getDriveId().toString());
                int s = ttDriveInfoMapper.insertSelective(record);
                if(s==1){
                    int a = ttTestdriveMapper.driveAgreement(testdrivePO.getDriveId().toString());
                    if (a == 1) {
                        result.put("errorCode", "1");
                        result.put("errorMsg", "上传试驾协议成功");
                    } else {
                        result.put("errorCode", "0");
                        result.put("errorMsg", "上传试驾协议失败，请重新处理");
                    }
                }else{
                    result.put("errorCode", "0");
                    result.put("errorMsg", "上传试驾协议失败，请重新处理");
                }
            } else {
                result.put("errorCode", "0");
                result.put("errorMsg", "上传试驾协议失败，请重新处理");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 完成试驾
     * 
     * @author Administrator
     * @date 2017年12月15日
     * @param driveId
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unused")
    public Map<String, Object> driveFinished(String driveId) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            int a = ttTestdriveMapper.driveFinished(driveId);
            if (a == 1) {
                logger.info("给该预约生成一个评价单");
                TtDriveEvaluation record = new TtDriveEvaluation();
                Integer evaluationId = ttDriveEvaluationMapper.selectId();
                record.setId(evaluationId);
                record.setEvaluationId(2);
                record.setOddNumber(driveId);
                record.setIfEvaluate(0);
                int b = ttDriveEvaluationMapper.insertEvaluation(record);
                if (b == 1) {
                    Example ex = new Example(TmEvaluationDetail.class);
                    ex.createCriteria().andCondition("EVALUATION_ID=", 2);
                    ex.setOrderByClause("DETAIL_ID ASC");
                    List<TmEvaluationDetail> list = tmEvaluationDetailMapper.selectByExample(ex);
                    for (int c = 0; c < list.size(); c++) {
                        TtDriveEvaluationResult records = new TtDriveEvaluationResult();
                        records.setCreateBy(DealerConstant.CREATE_USER);
                        records.setCreateDate(new Date());
                        records.setEvaluationDetailId(list.get(c).getDetailId());
                        records.setEvaluationDetailName(list.get(c).getStarContent());
                        records.setResultId(evaluationId);
                        records.setStarSum(0);
                        int d = ttDriveEvaluationResultMapper.insertSelective(records);
                    }
                    result.put("errorCode", "1");
                    result.put("errorMsg", "已成功完成试驾");
                    result.put("list", list);
                } else {
                    result.put("errorCode", "0");
                    result.put("errorMsg", "完成试驾异常，请重试");
                }
            } else {
                result.put("errorCode", "0");
                result.put("errorMsg", "完成试驾失败，请重新处理");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 立即评价
     * 
     * @author Administrator
     * @date 2017年12月15日
     * @param ttDriveEvaluation
     * @return
     * @throws Exception
     */
    public Map<String, Object> evaluate(EvaluationPO evaluationPO) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            String backUrl = "";
            List<String> mediaList = DloadImgFromQy.downloadMedia(evaluationPO.getDriveMediaIdList(),
                                                                  evaluationPO.getAccessToken());
            if (mediaList.size() != 0) {
                for (int i = 0; i < mediaList.size(); i++) {
                    if (i == 0) {
                        backUrl = mediaList.get(i);
                    } else {
                        backUrl = backUrl + ";" + mediaList.get(i);
                    }
                }
            }
            Example example = new Example(TtDriveEvaluation.class);
            example.createCriteria().andCondition("ODD_NUMBER=", evaluationPO.getOddNumber());
            List<TtDriveEvaluation> list = ttDriveEvaluationMapper.selectByExample(example);
            if (list.size() > 0) {
                Example ex = new Example(TtDriveEvaluation.class);
                ex.createCriteria().andCondition("RESULT_ID=", list.get(0).getId());
                List<TtDriveEvaluationResult> resultList = ttDriveEvaluationResultMapper.selectByExample(ex);
                if (resultList.size() > 0) {
                    List<EvaluationResultPO> param = evaluationPO.getList();
                    if (param.size() > 0) {
                        for (EvaluationResultPO p : param) {
                            TtDriveEvaluationResult records = new TtDriveEvaluationResult();
                            records.setUpdateBy(DealerConstant.UPDATE_USER);
                            records.setUpdateDate(new Date());
                            records.setStarSum(p.getStarSum());
                            ex.createCriteria().andCondition("EVALUATION_DETAIL_ID=", p.getEvaluationDetailId()).andCondition("RESULT_ID=", list.get(0).getId());
                            int s = ttDriveEvaluationResultMapper.updateByExampleSelective(records, ex);
                            logger.info("更新了" + s + "个评论的星级");
                        }
                        TtDriveEvaluation record = new TtDriveEvaluation();
                        record.setBackUrl(backUrl);
                        record.setEvaluationContent(evaluationPO.getEvaluationContent());
                        record.setIfEvaluate(1);
                        record.setUpdateBy(DealerConstant.UPDATE_USER);
                        record.setUpdateDate(new Date());
                        int a = ttDriveEvaluationMapper.updateByExampleSelective(record, example);
                        if (a == 1) {
                            result.put("errorCode", "1");
                            result.put("errorMsg", "评价成功");
                        } else {
                            result.put("errorCode", "0");
                            result.put("errorMsg", "评价失败");
                        }
                    } else {
                        result.put("errorCode", "0");
                        result.put("errorMsg", "请选择评价星级");
                    }
                } else {
                    result.put("errorCode", "0");
                    result.put("errorMsg", "该评价不存在");
                }
            } else {
                result.put("errorCode", "0");
                result.put("errorMsg", "该评价不存在");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 首席顾问列表
     * 
     * @author Administrator
     * @date 2017年12月18日
     * @param phone
     * @return
     * @throws Exception
     */
    public List<TmUsers> counselor(String dealerCode) throws Exception {
        List<TmUsers> resultList = new ArrayList<TmUsers>();
        try {
            resultList = tmUsersMapper.counselor(dealerCode);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
        return resultList;
    }

    /**
     * 鉴赏工程师列表
     * 
     * @author Administrator
     * @date 2017年12月18日
     * @param phone
     * @return
     * @throws Exception
     */
    public List<TmUsers> engineer(String licenseNo) throws Exception {
        List<TmUsers> resultList = new ArrayList<TmUsers>();
        try {
            resultList = tmUsersMapper.engineer(licenseNo);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
        return resultList;
    }

    /**
     * 分拨对象列表
     * 
     * @author Administrator
     * @date 2017年12月19日
     * @param regionCode
     * @return
     * @throws Exception
     */
    public List<TmVirtualCenter> dispatch(String driveId) throws Exception {
        List<TmVirtualCenter> resultList = new ArrayList<TmVirtualCenter>();
        try {
            resultList = tmVirtualCenterMapper.selectDisPatch(driveId);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
        return resultList;
    }

    /**
     * 省市列表
     * 
     * @author Administrator
     * @date 2017年12月19日
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> cityList() throws Exception {
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        try {
            Example ex = new Example(TmRegion.class);
            ex.createCriteria().andCondition("PARENT_CODE=", "0");
            List<TmRegion> provinceList = tmRegionMapper.selectByExample(ex);
            if (provinceList.size() > 0) {
                for (TmRegion dto : provinceList) {
                    Map<String, Object> firstMap = new HashMap<String, Object>();
                    Example example = new Example(TmRegion.class);
                    example.createCriteria().andCondition("PARENT_CODE=", dto.getRegionCode());
                    List<TmRegion> cityList = tmRegionMapper.selectByExample(example);
                    if (cityList.size() > 0) {
                        List<Map<String, Object>> deList = new ArrayList<Map<String, Object>>();
                        for (TmRegion child : cityList) {
                            Map<String, Object> deMap = new HashMap<String, Object>();
                            deMap.put("label", child.getRegionName());
                            deMap.put("value", child.getRegionCode());
                            deList.add(deMap);
                        }
                        firstMap.put("label", dto.getRegionName());
                        firstMap.put("value", dto.getRegionCode());
                        firstMap.put("children", deList);
                    }
                    resultList.add(firstMap);
                }
                // Map<String, Object> result = new HashMap<String, Object>();
                // result = wXServiceInterface.accessToken();
                // logger.info("测试接口返回值：" + result);
            } else {
                throw new ServiceBizException("违章查询支持城市列表为空");
            }
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
        return resultList;
    }

    /**
     * 接单选择销售店列表
     * 
     * @author Administrator
     * @date 2017年12月21日
     * @param userId
     * @param phone
     * @return
     * @throws Exception
     */
    public List<TmDealer> dealer(String userId, String phone) throws Exception {
        List<TmDealer> resultList = new ArrayList<TmDealer>();
        try {
            resultList = tmDealerMapper.selectDealer(userId, phone);
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
        return resultList;
    }

    /**
     * 车型列表
     * 
     * @author Administrator
     * @date 2017年12月21日
     * @return
     * @throws Exception
     */
    public List<Map<String, String>> carModel() throws Exception {
        List<Map<String, String>> resultList = new ArrayList<Map<String, String>>();
        try {
            resultList = tmDealerMapper.selectCarModel();
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
        return resultList;
    }

    /**
     * 状态列表
     * 
     * @author Administrator
     * @date 2017年12月27日
     * @return
     * @throws Exception
     */
    public List<Map<String, String>> status() throws Exception {
        List<Map<String, String>> resultList = new ArrayList<Map<String, String>>();
        try {
            resultList = tmDealerMapper.selectStatus();
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
        return resultList;
    }

    /**
     * PC-经理列表
     * 
     * @author Administrator
     * @date 2017年12月27日
     * @return
     * @throws Exception
     */
    public List<TmUsers> managers() throws Exception {
        List<TmUsers> resultList = new ArrayList<TmUsers>();
        try {
            Example example = new Example(TmUsers.class);
            example.createCriteria().andCondition("VIRTUAL_CENTER IS NOT NULL");
            resultList = tmUsersMapper.selectByExample(example);
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
        return resultList;
    }

    /**
     * PC-顾问列表
     * 
     * @author Administrator
     * @date 2017年12月27日
     * @return
     * @throws Exception
     */
    public List<TmUsers> counselors() throws Exception {
        List<TmUsers> resultList = new ArrayList<TmUsers>();
        try {
            resultList = tmUsersMapper.counselors();
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
        return resultList;
    }

    /**
     * PC-工程师列表
     * 
     * @author Administrator
     * @date 2017年12月27日
     * @return
     * @throws Exception
     */
    public List<TmUsers> engineers() throws Exception {
        List<TmUsers> resultList = new ArrayList<TmUsers>();
        try {
            resultList = tmUsersMapper.engineers();
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
        return resultList;
    }

    /**
     * 车辆列表
     * 
     * @author Administrator
     * @date 2017年12月21日
     * @param driveId
     * @param modelCodeNew
     * @return
     * @throws Exception
     */
    public List<String> carList(String driveId, String modelCodeNew) throws Exception {
        List<String> resultList = new ArrayList<String>();
        try {
            resultList = tmDealerMapper.selectCarInfo(driveId, modelCodeNew);
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
        return resultList;
    }
    
    public List<String> dispatchCarList(String dispatchObject, String modelCodeNew) throws Exception {
        List<String> resultList = new ArrayList<String>();
        try {
            resultList = tmDealerMapper.dispatchObject(dispatchObject, modelCodeNew);
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
        return resultList;
    }

    /**
     * 查看资源占用
     * 
     * @author Administrator
     * @date 2017年12月21日
     * @param date
     * @return
     * @throws Exception
     */
    public PageInfo<Map<String, Object>> resourceUsage(Integer pageNum,Integer pageSize,String date, String dispatchObject, String dealerCode,
                                                   String modelCodeNew) throws Exception {
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        try {
            if (CheckUtil.NullOrEmpty(date)) {
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                Calendar c = Calendar.getInstance();
                c.add(Calendar.DAY_OF_MONTH, 1);
                date = sf.format(c.getTime());
            }
            Page<Map<String, String>> ss = PageHelper.startPage(pageNum,pageSize);
            List<Map<String, String>> carList = tmDealerMapper.selectCarList(dispatchObject, dealerCode, modelCodeNew);
            if (carList.size() != 0) {
                for (Map<String, String> m : carList) {
                    List<Map<String, String>> usageList = tmDealerMapper.selectUsage(m.get("licenseNo"), date);

                    Map<String, Object> map = new HashMap<String, Object>();
                    List<FreeTimeDto> list = new ArrayList<>();
                    FreeTimeDto e = new FreeTimeDto();
                    e.setBeginTime("09");
                    e.setEndTime("18");
                    list.add(e);
                    List<Map<String, String>> timeList = new ArrayList<Map<String, String>>();

                    String l1 = "";
                    String l2 = "";
                    String l3 = "";
                    String l4 = "";
                    String l5 = "";

                    for (FreeTimeDto freeTimeDto : list) {
                        Date d = DateUtil.dateFormat(freeTimeDto.getBeginTime() + ":00:00", "HH:mm:ss");
                        Calendar beginTime = Calendar.getInstance();
                        beginTime.setTime(d);
                        // 30分钟为间隔
                        Date dateEnd = DateUtil.dateFormat(freeTimeDto.getEndTime() + ":00:00", "HH:mm:ss");
                        Calendar endTime = Calendar.getInstance();
                        endTime.setTime(dateEnd);
                        // 结束时间-30分钟
                        endTime.add(Calendar.MINUTE, -30);
                        String resource = "";
                        String time = String.format("%02d", beginTime.get(Calendar.HOUR_OF_DAY)) + ":"
                                      + String.format("%02d", beginTime.get(Calendar.MINUTE));
                        for (Map<String, String> l : usageList) {
                            Date da = DateUtil.dateFormat(l.get("applyTime"), "HH:mm");
                            Calendar tm = Calendar.getInstance();
                            tm.setTime(da);
                            tm.add(Calendar.MINUTE, -60);
                            l1 = String.format("%02d", tm.get(Calendar.HOUR_OF_DAY)) + ":"
                                 + String.format("%02d", tm.get(Calendar.MINUTE));
                            tm.setTime(da);
                            tm.add(Calendar.MINUTE, -30);
                            l2 = String.format("%02d", tm.get(Calendar.HOUR_OF_DAY)) + ":"
                                 + String.format("%02d", tm.get(Calendar.MINUTE));
                            tm.setTime(da);
                            tm.add(Calendar.MINUTE, 30);
                            l3 = String.format("%02d", tm.get(Calendar.HOUR_OF_DAY)) + ":"
                                 + String.format("%02d", tm.get(Calendar.MINUTE));
                            tm.setTime(da);
                            tm.add(Calendar.MINUTE, 60);
                            l4 = String.format("%02d", tm.get(Calendar.HOUR_OF_DAY)) + ":"
                                 + String.format("%02d", tm.get(Calendar.MINUTE));
                            tm.setTime(da);
                            tm.add(Calendar.MINUTE, 90);
                            l5 = String.format("%02d", tm.get(Calendar.HOUR_OF_DAY)) + ":"
                                 + String.format("%02d", tm.get(Calendar.MINUTE));
                            if (time.equals(l) || time.equals(l1) || time.equals(l2) || time.equals(l3)
                                || time.equals(l4) || time.equals(l5)) {
                                resource = l.get("userName");
                            }
                        }
                        Map<String, String> timeMap = new HashMap<String, String>();
                        timeMap.put("time", time);
                        timeMap.put("resource", resource);
                        timeList.add(timeMap);
                        while (!endTime.before(beginTime)) {// 让最后一个时间出现
                            // 30分钟为间隔
                            beginTime.add(Calendar.MINUTE, 30);
                            resource = "";
                            time = String.format("%02d", beginTime.get(Calendar.HOUR_OF_DAY)) + ":"
                                   + String.format("%02d", beginTime.get(Calendar.MINUTE));
                            for (Map<String, String> l : usageList) {
                                Date da = DateUtil.dateFormat(l.get("applyTime"), "HH:mm");
                                Calendar tm = Calendar.getInstance();
                                tm.setTime(da);
                                tm.add(Calendar.MINUTE, -60);
                                l1 = String.format("%02d", tm.get(Calendar.HOUR_OF_DAY)) + ":"
                                     + String.format("%02d", tm.get(Calendar.MINUTE));
                                tm.setTime(da);
                                tm.add(Calendar.MINUTE, -30);
                                l2 = String.format("%02d", tm.get(Calendar.HOUR_OF_DAY)) + ":"
                                     + String.format("%02d", tm.get(Calendar.MINUTE));
                                tm.setTime(da);
                                tm.add(Calendar.MINUTE, 30);
                                l3 = String.format("%02d", tm.get(Calendar.HOUR_OF_DAY)) + ":"
                                     + String.format("%02d", tm.get(Calendar.MINUTE));
                                tm.setTime(da);
                                tm.add(Calendar.MINUTE, 60);
                                l4 = String.format("%02d", tm.get(Calendar.HOUR_OF_DAY)) + ":"
                                     + String.format("%02d", tm.get(Calendar.MINUTE));
                                tm.setTime(da);
                                tm.add(Calendar.MINUTE, 90);
                                l5 = String.format("%02d", tm.get(Calendar.HOUR_OF_DAY)) + ":"
                                     + String.format("%02d", tm.get(Calendar.MINUTE));
                                if (time.equals(l) || time.equals(l1) || time.equals(l2) || time.equals(l3)
                                    || time.equals(l4) || time.equals(l5)) {
                                    resource = l.get("userName");
                                }
                            }
                            Map<String, String> tm = new HashMap<String, String>();
                            tm.put("time", time);
                            tm.put("resource", resource);
                            timeList.add(tm);
                        }
                    }
                    map.put("centerName", m.get("centerName"));
                    map.put("dealerName", m.get("dealerName"));
                    map.put("modelName", m.get("modelName"));
                    map.put("licenseNo", m.get("licenseNo"));
                    map.put("timeList", timeList);
                    resultList.add(map);
                }
                PageInfo<Map<String, Object>> page = new PageInfo<Map<String, Object>>(resultList);
                return page;
            } else {
                throw new ServiceBizException("暂无可看资源");
            }
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
     * 查看资源-分拨对象列表
     * 
     * @author Administrator
     * @date 2017年12月25日
     * @return
     * @throws Exception
     */
    public List<TmVirtualCenter> resourceObject() throws Exception {
        List<TmVirtualCenter> resultList = new ArrayList<TmVirtualCenter>();
        try {
            resultList = tmVirtualCenterMapper.selectAll();
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
        return resultList;
    }

    /**
     * 查看资源-经销商列表
     * 
     * @author Administrator
     * @date 2017年12月25日
     * @return
     * @throws Exception
     */
    public List<TmDealer> resourceDealer() throws Exception {
        List<TmDealer> resultList = new ArrayList<TmDealer>();
        try {
            resultList = tmDealerMapper.selectAll();
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
        return resultList;
    }

    public String selectRelation(String wxUserId, String phone) throws Exception {
        try {
            String relation = tmUsersMapper.selectRelation(wxUserId, phone);
            return relation;
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
     * 行前确认-物品列表
     * 
     * @author Administrator
     * @date 2017年12月27日
     * @return
     * @throws Exception
     */
    public List<TtDriveGoods> goodsList() throws Exception {
        List<TtDriveGoods> resultList = new ArrayList<TtDriveGoods>();
        try {
            resultList = ttDriveGoodsMapper.selectAll();
            return resultList;
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }
    
    /**
    * 新增试驾人
    * @author Administrator
    * @date 2017年12月28日
    * @param ttDriveInfo
    * @return
    * @throws Exception
    */
    public Map<String, Object> addDriver(TtDriveInfo ttDriveInfo) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try{
            Example example = new Example(TtDriveInfo.class);
            example.createCriteria().andCondition("DRIVE_ID=", ttDriveInfo.getDriveId());
            List<TtDriveInfo> list = ttDriveInfoMapper.selectByExample(example);
            if(list.size()!=0){
                int a = ttDriveInfoMapper.updateByExampleSelective(ttDriveInfo, example);
                if (a == 1) {
                    result.put("errorCode", "1");
                    result.put("errorMsg", "新增试驾人成功");
                } else {
                    result.put("errorCode", "0");
                    result.put("errorMsg", "新增试驾人失败");
                }
            }else{
                int a = ttDriveInfoMapper.insertSelective(ttDriveInfo);
                if (a == 1) {
                    result.put("errorCode", "1");
                    result.put("errorMsg", "新增试驾人成功");
                } else {
                    result.put("errorCode", "0");
                    result.put("errorMsg", "新增试驾人失败");
                }
            }
            
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
        return result;
    }
    
    public PageInfo<TtTestdrive> oemList(Integer pageNum,String pageSize) throws Exception {
        List<TtTestdrive> list = new ArrayList<TtTestdrive>();
        try {
            Page<TtTestdrive> ss = PageHelper.startPage(pageNum,Integer.parseInt(pageSize));
            list = ttTestdriveMapper.oemList();
            PageInfo<TtTestdrive> page = new PageInfo<TtTestdrive>(list);
            return page;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
    }
}
